package com.gcph.zhuoba.main.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.gcph.zhuoba.R;
import com.gcph.zhuoba.util.L;
import com.gcph.zhuoba.util.PicLoadUtil;
/**
 * 球桌页面
 */
public class BallJiasaiDisplayView extends SurfaceView implements SurfaceHolder.Callback{
	//定义画笔
	private Paint paint; 		
	//定义画布
	private Canvas canvas = null; 
	private SurfaceHolder sfh = null;
	
	//获取视图的宽度
	private int screenW = 0;
	//获取视图的高度
	private int screenH = 0;
	private int imgW = 0;
	private Bitmap bitmap =null;
	private float fitx =0;
	
	//半径
	private float radius = 0;
	
	private float jiasaiX=0f;
	private float jiasaiY=0f;
	
	public void setJiasai(float x,float y)
	{
		L.d("===setJiasai");
		jiasaiX = x;
		jiasaiY = y;
		
		int cx = (int)(jiasaiX*radius+screenW/2f);
		int cy = (int)(jiasaiY*radius+radius);
		myDraw(cx,cy);
	}
	
	public BallJiasaiDisplayView(Context context,AttributeSet attrs){
		super(context,attrs);
		initPaint();
		sfh = getHolder();
		sfh.addCallback(this);
	}
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		
		//获取视图的宽度
		screenW = getWidth();
		//获取视图的高度
		screenH = getHeight();
		bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ball_jiasai);
		imgW = bitmap.getWidth();
		
		L.d("screenW="+screenW);
		L.d("screenH="+screenH);
		L.d("imgW="+imgW);
		
		fitx=(screenW-screenH)/2f;
		
		radius = screenH/2f;
	}
	
	/**
	 * 初始化画笔
	 */
	private void initPaint(){
		paint = new Paint();
		//设置消除锯齿
		paint.setAntiAlias(true);
	}
	
	 public void myDraw(int cx,int cy) {
		//获取canvas实例
		canvas = sfh.lockCanvas();
		
		L.d("myDraw=cx=cy=canvas="+cx+","+cy+","+canvas);
		canvas.drawColor(Color.WHITE);
		canvas.drawBitmap(PicLoadUtil.scaleToFit(bitmap,(screenW-2*fitx)/imgW+0.0f),fitx, 0, paint);
		
		paint.setColor(Color.RED);
		canvas.drawCircle(cx, cy, screenH/10, paint);
		paint.setColor(Color.WHITE);
		canvas.drawCircle(cx, cy, screenH/12, paint);
		
		sfh.unlockCanvasAndPost(canvas);
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		L.d( "surfaceChanged");
	}
	
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		L.d( "surfaceDestroyed");
	}
}